<?php
require_once 'Zend/View/Interface.php';
require_once 'Smarty/Smarty.class.php';

class Okute_View_Smarty implements Zend_View_Interface
{
    protected $_smarty;
    protected $_lang;

    public function __construct($tmplPath = null, $extraParams = array(), $extraFuncs = array())
    {
        $this->_smarty = new Smarty;

        if(null !== $tmplPath)
        {
            $this->setScriptPath($tmplPath);
        }

        foreach ($extraParams as $key => $value)
        {
            $this->_smarty->$key = $value;
        }

        foreach ($extraFuncs as $key => $value)
        {
            call_user_func_array(array($this->_smarty, $key), $value);
        }
    }

    public function getEngine()
    {
        return $this->_smarty;
    }

    public function setScriptPath($path)
    {
        if(is_readable($path))
        {
            $this->_smarty->template_dir = $path;
            return;
        }
        throw new Exception('無効なパスが指定されました');
    }

    public function getScriptPath()
    {
        return $this->_smarty->template_dir;
    }

    public function __set($key, $val)
    {
        $this->_smarty->assign($key, $val);
    }

    public function __get($key)
    {
        return $this->_smarty->getTemplateVars($key);
    }

    public function __isset($key)
    {
        return (null !== $this->_smarty->getTemplateVars($key));
    }

    public function __unset($key)
    {
        $this->_smarty->clear_assign($key);
    }

    public function assign($spec, $value = null)
    {
        if(is_array($spec))
        {
            $this->_smarty->assign($spec);
            return;
        }

        $this->_smarty->assign($spec, $value);
    }

    public function assignByRef(&$spec, &$value = null)
    {
        if(is_array($spec))
        {
            $this->_smarty->assign_by_ref($spec);
            return;
        }

        $this->_smarty->assign_by_ref($spec, $value);
    }

    public function clearVars()
    {
        $this->_smarty->clear_all_assign();
    }

    public function render($name)
    {
        return $this->_smarty->fetch($name);
    }

    public function getScriptPaths()
    {
        return array($this->_smarty->template_dir);
    }

    public function setBasePath($path, $classPrefix = 'Zend_View')
    {
    }

    public function addBasePath($string, $classPrefix = 'Zend_View')
    {
    }

    public function addPluginsDir($plugins_dir)
    {
        $this->_smarty->plugins_dir[] = $plugins_dir;
    }

    public function loadFilter($type, $name)
    {
        $this->_smarty->loadFilter($type, $name);
    }

    public static function getOutputFilterName($charset)
    {
        // charset => function
        $filters = array(
            'SJIS'      => 'sjis',
            'Shift_JIS' => 'sjis',
            'EUC-JP'    => 'euc',
            'UTF-8'     => 'utf8');
        $func = isset($filters[$charset]) ? $filters[$charset] : $charset;
        return $func;
    }

}